package com.tj.tj_java.service.impl;

import com.tj.tj_java.dto.UserLoginDto;
import com.tj.tj_java.dto.UserCredentialsDto;
import com.tj.tj_java.mapper.VerificationMapper;
import com.tj.tj_java.mapper.UserMapper;
import com.tj.tj_java.pojo.Verification;
import com.tj.tj_java.pojo.User;
import com.tj.tj_java.result.Result;
import com.tj.tj_java.service.UserService;
import com.tj.tj_java.utils.ExpirationTimeUtils;
import com.tj.tj_java.utils.MD5Utils;
import com.tj.tj_java.utils.QQEmailValidatorUtils;
import com.tj.tj_java.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tj.tj_java.utils.VerificationCodeUtils;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;

//声明注解他是service类
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper; //用户mapper

    @Autowired
    private VerificationCodeUtils verificationCodeUtils;//验证码工具类

    @Autowired
    private VerificationMapper verificationMapper;  //验证码mapper

    //用户登录的实现类
    @Override
    public Result login(UserLoginDto userLoginDto) {
        //用户名和密码
        String userName = userLoginDto.getName();
        String password = userLoginDto.getPassword();
        //调用mapper层,根据用户名获取用户信息
        User user = userMapper.getUserByName(userName);
        //判断用户是否存在
        if (user == null) {
            return Result.error("该用户不存在");
        }
        //使用MD5加密工具对前端传输过来的明文密码进行加密，再进行对比(因为数据库中存储的密码是加密后的)
        password=MD5Utils.inputPassToFormPass(password);
        // 输入的密码不等于数据库中密码 = false
        if(!Objects.equals(user.getPassword(), password)){
            return Result.error("密码错误");
        }
        //创建用户返回类对象
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .userId(user.getUserId())
                .email(user.getEmail())
                .name(user.getName())
                .build();
        return Result.success("登录成功",userLoginVo);
    }


    //发送验证码
    @Override
    public Result SendVerificationCode(String email,String codeType) {
        //调用QQ邮箱校验工具类判断前端传递的参数是否为正确的qq邮箱格式
        boolean validQQEmail = QQEmailValidatorUtils.isValidQQEmail(email);
        if (!validQQEmail) {
            return Result.error("邮箱格式不正确");
        }
        //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
        Timestamp timestamp = Timestamp.valueOf(localDateTime);
        //查询 已发送验证码 且 验证码未过期 的邮箱 - verification
        Verification verification = verificationMapper.getVerificationByEmailAndTimeAndCodeType(email,timestamp,codeType);
        if(verification != null){//不等于空说明查到了数据
            return Result.error("验证码已下发！5分钟内有效！请勿重新发送！");
        }
        //删除所以过期邮箱
        verificationMapper.deleteTimeoutCode(timestamp);
        //调用发送验证码工具类，传入需要发送的邮箱，获取随机生成的的验证码
        int code = verificationCodeUtils.sendCode(email);
        //调用获取过期时间工具类，获取过期时间
        Timestamp expirationTime = ExpirationTimeUtils.getExpirationTime();
        //调用mapper，将邮箱、对应的验证码、过期时间、验证码类型、存入数据库
        verificationMapper.saveCode(email,code,expirationTime,codeType);
        return Result.success("验证码发送成功");
    }

    @Override//用户注册实现类
    public Result register(UserCredentialsDto userCredentialsDto) {
        //根据 name和邮箱 查询 用户 是否已经存在（name和Email唯一）
        if (userMapper.getUserByName(userCredentialsDto.getName()) != null) {
            return Result.error("该用户名已被使用");
        } else if (userMapper.getUserByEmail(userCredentialsDto.getEmail()) != null) {
            return Result.error("该邮箱已经被注册！");
        }
        //判断验证码是否正确
        Verification verification = verificationMapper.getVerificationByEmailAndCode(userCredentialsDto.getEmail(), userCredentialsDto.getVerifyCode(), userCredentialsDto.getCodeType());
        if (verification == null) {
            return Result.error("验证码错误");
        }
        //将前端传递的明文密码进行MD5加密，再存入数据库
        userCredentialsDto.setPassword(MD5Utils.inputPassToFormPass(userCredentialsDto.getPassword()));
        //调用mapper实现注册
        userMapper.addUser(userCredentialsDto);
        //注册成功后删除验证码表中该邮箱验证码信息，预防多次使用该验证码注册
        verificationMapper.deleteCode(userCredentialsDto.getEmail(), userCredentialsDto.getCodeType());

        return Result.success("注册成功",userMapper.getUserByName(userCredentialsDto.getName()));
    }


    //修改密码
    @Override
    public Result updatePassword(UserCredentialsDto userCredentialsDto) {
        //判断该邮箱是否注册
        if (userMapper.getUserByEmail(userCredentialsDto.getEmail()) == null) {
            return Result.error("该邮箱还没有注册账号，你修改啥密码?");
        }
        //判断验证码是否正确
        Verification verification = verificationMapper.getVerificationByEmailAndCode(userCredentialsDto.getEmail(), userCredentialsDto.getVerifyCode(), userCredentialsDto.getCodeType());
        if (verification == null) {
            return Result.error("验证码错误");
        }
        //根据邮箱获取id
        int id = userMapper.getUserIdByEmail(userCredentialsDto.getEmail());
        //对新密码进行加密
        userCredentialsDto.setPassword(MD5Utils.inputPassToFormPass(userCredentialsDto.getPassword()));
        //加密后的新密码
        String newPassword = userCredentialsDto.getPassword();
        //修改密码成功后后删除验证码记录
        verificationMapper.deleteCode(userCredentialsDto.getEmail(), userCredentialsDto.getCodeType());
        //根据id修改密码
        userMapper.updatePassword(newPassword,id);
        return Result.success("修改密码成功");
    }
}




